package com.gukun.springboot.tdengine.service.collectormanage;

import com.gukun.springboot.tdengine.dao.TDEngineDao;
import com.gukun.springboot.tdengine.dto.SubmitTableDto;
import com.gukun.springboot.tdengine.pojo.DBConfig;
import com.gukun.springboot.tdengine.pojo.TagInfo;
import com.gukun.springboot.tdengine.service.TDEngineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class CollectormanageService {
    @Autowired
    private TDEngineService tdEngineService;
    public void submitTableData(SubmitTableDto submitTableDto) throws SQLException {
        if(submitTableDto != null && submitTableDto.getDbConfig() != null && submitTableDto.getTagInfo() != null){
            DBConfig dbConfig = submitTableDto.getDbConfig();
            TDEngineDao tdEngineDao = tdEngineService.getTDEngineDao(dbConfig.getHost(), dbConfig.getPort(),
                    dbConfig.getUsername(), dbConfig.getPassword(), dbConfig.getDbName());
            tdEngineDao.useDb(dbConfig.getDbName());

            TagInfo tagInfo = submitTableDto.getTagInfo();
            if(tagInfo != null && tagInfo.getTagName() != null && !Objects.equals(tagInfo.getTagName(), "")){
                String sql = "select table_name from information_schema.ins_tables where db_name = '"+dbConfig.getDbName()+"' and table_name = '"+tagInfo.getTagName()+"' ";
                try(ResultSet resultSet = tdEngineDao.executeQuery(sql)) {
                    if (resultSet.next()) {
                        //存在表，那么进行表信息修改
                        String updateTiSql = "ALTER TABLE " + dbConfig.getDbName() + "." + tagInfo.getTagName() + " SET TAG ti=\"" + tagInfo.toString() + "\"";
                        String updateTnSql = "ALTER TABLE " + dbConfig.getDbName() + "." + tagInfo.getTagName() + " SET TAG tn=\"" + tagInfo.getTn() + "\"";
                        String updateTaSql = "ALTER TABLE " + dbConfig.getDbName() + "." + tagInfo.getTagName() + " SET TAG ta=\"" + tagInfo.getTa() + "\"";
                        tdEngineDao.executeUpdateSQL(updateTiSql);
                        tdEngineDao.executeUpdateSQL(updateTnSql);
                        tdEngineDao.executeUpdateSQL(updateTaSql);
                    } else {
                        //不存在表，那么进行表信息创建
                        List<TagInfo> tagInfoList = new ArrayList<>();
                        tagInfo.setTags(tagInfo.toString());
                        tagInfo.setTi(tagInfo.toString());
                        tagInfoList.add(tagInfo);
                        tdEngineDao.createTables(tagInfoList);
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    throw new SQLException("Error executing SQL: " + sql, e);
                }
            }
        }
    }

}
